package com.example.user.biz.service.impl;

import com.example.common.context.BaseContext;
import com.example.user.biz.domain.dto.AddAddressDTO;
import com.example.user.biz.domain.dto.AddressDTO;
import com.example.user.biz.domain.po.Address;
import com.example.user.biz.domain.vo.AddressVO;
import com.example.user.biz.mapper.AddressMapper;
import com.example.user.biz.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;
    /**
     * 查询当前用户地址列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<AddressVO> findMyAddresses(Long userId) {
        Address address = Address.builder()
                .userId(userId)
                .build();
        List<AddressVO> list = addressMapper.list(address);
        return list;
    }

    /**
     * 添加收货地址
     *
     * @param addressDTO
     */
    @Override
    public void addAddress(AddAddressDTO addressDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        address.setUserId(BaseContext.getCurrentId());
        if (address.getIsDefault() == 1) {
            //将当前用户所有地址修改为非默认地址
            address.setIsDefault(0);
            addressMapper.updateIsDefaultByUserId(address);
            address.setIsDefault(1);
        }

        addressMapper.insert(address);

    }

    /**
     * 删除收货地址
     *
     * @param id
     */
    @Override
    public void deleteAddress(Integer id) {
        addressMapper.deleteAddress(id);
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressVO findById(Integer id) {
        Address address = Address.builder()
                .id(id)
                .build();
        List<AddressVO> list = addressMapper.list(address);
        if (list != null && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 修改收货地址
     *
     * @param addressDTO
     */
    @Override
    public void updateAddress(AddressDTO addressDTO) {
        Address address=new Address();
        //将dto对象复制到pojo对象
        BeanUtils.copyProperties(addressDTO,address);
        address.setUserId(BaseContext.getCurrentId());
        if (address.getIsDefault() == 1) {
            //将当前用户所有地址修改为非默认地址
            address.setIsDefault(0);
            addressMapper.updateIsDefaultByUserId(address);
            address.setIsDefault(1);
        }
        addressMapper.update(address);
    }
}
